package com.wnhz.work.yz.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.wnhz.work.yz.MainActivity;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.activity.ChuFangActivity;
import com.wnhz.work.yz.activity.EntiretyBathroomActivity;
import com.wnhz.work.yz.activity.IndustryFitmentActivity;
import com.wnhz.work.yz.activity.InstallActivity;
import com.wnhz.work.yz.adapter.HomePageListAdapter;
import com.wnhz.work.yz.adapter.HomePageRecycleAdapter;
import com.wnhz.work.yz.adapter.MyViewPagerAdapter;
import com.wnhz.work.yz.bean.BannerBean;
import com.wnhz.work.yz.bean.HomePageListBean;
import com.wnhz.work.yz.bean.HomePageRecycleBean;
import com.wnhz.work.yz.utils.AddImages;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.NoScrollListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * ---首页
 */
public class Home1HomePage extends Fragment implements View.OnClickListener {
    private View view;
    private PullToRefreshScrollView myScroll;
    private ScrollView scrollView;
    private ViewPager viewPager;
    private LinearLayout indicatorLayout;

    private ArrayList<View> viewList = new ArrayList<>();// 添加了首尾的轮播图集合
    private List<String> autoPlayImages = new ArrayList<>();// 轮播图的图片资源集合
    private int currentPosition;
    private ImageView[] indicators;
    private MainActivity mainActivity;

    private RecyclerView rv_homePage;
    private NoScrollListView homePage_listView;
    private HomePageListAdapter listAdapter;

    private List<HomePageRecycleBean> recycleList = new ArrayList<>();
    private HomePageRecycleAdapter recycleAdapter;

    private List<BannerBean> bannerlist = new ArrayList<>();
    private MyViewPagerAdapter bannerAdapter;

    private List<HomePageListBean> pagelist = new ArrayList<>();
    private List<HomePageListBean> pagelist2 = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home1_home_page, container, false);
        mainActivity = (MainActivity) getActivity();
        initData();
        initView();
        return view;
    }

    private int pager = 0, nums = 6;
    private boolean isMore;

    private void initData() {
        myScroll = (PullToRefreshScrollView) view.findViewById(R.id.myScroll);

        myScroll.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                myScroll.onRefreshComplete();
                pagelist2.clear();
                pagelist.clear();
                isMore = false;
                pager = 0;
                loadGoods();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //  Toast.makeText(mainActivity, "加载完成", Toast.LENGTH_SHORT).show();
                myScroll.onRefreshComplete();
                if (pagelist == null || pagelist.size() <= 0) {
                    mainActivity.MyToast("没有更多了!");
                }
                for (int i = 0; i < nums; i++) {
                    Log.e(nums + "---" + pager, pagelist2.size() + "--" + pagelist.size());
                    if (pagelist2.size() >= pagelist.size()) {
                        isMore = true;
                        continue;
                    }
                    pagelist2.add(pagelist.get(i + nums * pager));
                }
                if (!isMore) {
                    pager++;
                }
                listAdapter.notifyDataSetChanged();
            }
        });

        scrollView = myScroll.getRefreshableView();
    }


    private void initView() {
        myScroll = (PullToRefreshScrollView) view.findViewById(R.id.myScroll);
        viewPager = (ViewPager) view.findViewById(R.id.homePager_viewpager);
        indicatorLayout = (LinearLayout) view.findViewById(R.id.homepager_indicator);

        view.findViewById(R.id.rl_home).setOnClickListener(this);//家居馆
        view.findViewById(R.id.rl_industry).setOnClickListener(this);//工业化内装
        view.findViewById(R.id.rl_bathroom).setOnClickListener(this);//整体卫浴
        view.findViewById(R.id.rl_install).setOnClickListener(this);//安装
        view.findViewById(R.id.rl_design).setOnClickListener(this);//设计
        view.findViewById(R.id.rl_chufang).setOnClickListener(this);//厨房
        rv_homePage = (RecyclerView) view.findViewById(R.id.rv_homePage);
        homePage_listView = (NoScrollListView) view.findViewById(R.id.homePage_listView);
        upload();

        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewPager.getLayoutParams();
        double d = 576.00 / 1080.00;
        params.height = (int) (width * d);
        viewPager.setLayoutParams(params);

        //设置限时购的recycle的显示方向
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_homePage.setLayoutManager(linearLayoutManager);
        recycleAdapter = new HomePageRecycleAdapter(getActivity(), recycleList);
        rv_homePage.setAdapter(recycleAdapter);

        //PullListView
        listAdapter = new HomePageListAdapter(getActivity(), pagelist2, this);
        homePage_listView.setAdapter(listAdapter);
    }

    @Override
    public void onResume() {
        if (listAdapter != null) {
            listAdapter.notifyDataSetChanged();
        }
        super.onResume();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        //upload();
        if (listAdapter != null) {
            listAdapter.notifyDataSetChanged();
        }
        super.onHiddenChanged(hidden);
    }


    private void loadGoods() {
        XUtil.Post(Url.GOODS_GETINDEXGOODS, null, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                mainActivity.closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: GOODS = " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    if ("1".equals(res)) {
                        pagelist.clear();
                        JSONArray jsonArray = jsonObject.optJSONArray("info");
                        if (jsonArray != null) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                HomePageListBean bean = new HomePageListBean();
                                Gson gson = new Gson();
                                bean = gson.fromJson(jsonArray.optString(i), HomePageListBean.class);

                                pagelist.add(bean);
                            }
                        }

                        listAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                mainActivity.closeDialog();
                for (int i = 0; i < nums; i++) {
                    Log.e(nums + "---" + pager, pagelist2.size() + "--" + pagelist.size());
                    if (pagelist2.size() >= pagelist.size()) {
                        isMore = true;
                        continue;
                    }
                    pagelist2.add(pagelist.get(i + nums * pager));
                }
                if (!isMore) {
                    pager++;
                }
                Log.e(nums + "=222---" + pager, pagelist2.size() + "--" + pagelist.size());
                listAdapter.notifyDataSetChanged();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mainActivity.closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private static final String TAG = "Home1HomePage";

    private void upload() {
        mainActivity.showDialog();
        XUtil.Post(Url.GOODS_GETBANNER, null, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                mainActivity.closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: frag1" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    JSONArray jsonArray = jsonObject.optJSONArray("info");
                    bannerlist.clear();

                    if (jsonArray != null) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            BannerBean bean = new BannerBean();
                            JSONObject j = jsonArray.getJSONObject(i);
                            String pic = j.optString("pic");
                            String url = j.optString("url");
                            bean.setPic(pic);
                            bean.setUrl(url);
                            bannerlist.add(bean);
                        }
                        Log.i(TAG, "onSuccess: bannerlist" + bannerlist.size());
                        autoPlayImages.clear();
                        for (int i = 0; i < bannerlist.size(); i++) {
                            autoPlayImages.add(bannerlist.get(i).getPic());
                        }
                        initViewPager();
                        setViewPager();
                        bannerAdapter.notifyDataSetChanged();
                    }
                    JSONObject res2 = new JSONObject(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                loadGoods();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mainActivity.closeDialog();
                super.onError(ex, isOnCallback);
                Log.i(TAG, "onError: Throwable" + ex);
            }
        });
    }

    private void setViewPager() {
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                currentPosition = arg0;
                if (currentPosition < 1) { // 首位之前，跳转到末尾（N）
                    setIndicator(autoPlayImages.size() - 1);
                } else if (currentPosition > autoPlayImages.size()) { // 末位之后，跳转到首位（1）
                    setIndicator(0);
                } else {

                    setIndicator(currentPosition - 1);
                }

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                if (arg0 == 0) {
                    handler.removeMessages(11);
                    Message message = new Message();
                    message.what = 11;
                    handler.sendMessageDelayed(message, 3000);
                    viewPager.setCurrentItem(currentPosition, false);
                    if (viewList.size() > 1) { // 多于1，才会循环跳转
                        if (currentPosition < 1) { // 首位之前，跳转到末尾（N）
                            currentPosition = autoPlayImages.size(); // 注意这里是mList，而不是mViews
                            viewPager.setCurrentItem(currentPosition, false);
                        } else if (currentPosition > autoPlayImages.size()) { // 末位之后，跳转到首位（1）
                            viewPager.setCurrentItem(currentPosition, true); // false:不显示跳转过程的动画
                            viewPager.setCurrentItem(1, false); // false:不显示跳转过程的动画
                            currentPosition = 1;
                        }
                    }
                }

            }
        });

        currentPosition = 1;
        setIndicator(0);
        viewPager.setCurrentItem(currentPosition, false);
        handler.removeMessages(11);
        Message message = new Message();
        message.what = 11;
        handler.sendMessageDelayed(message, 3000);
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 11:
//                    Toast.makeText(getActivity(),currentPosition+"",Toast.LENGTH_LONG).show();
                    int position = currentPosition + 1;
                    viewPager.setCurrentItem(position, true);
                    break;

                default:
                    break;
            }
        }

    };


    /**
     * 设置指示器
     *
     * @param selectedPosition 默认指示器位置
     */
    private void setIndicator(int selectedPosition) {


        for (int i = 0; i < indicators.length; i++) {
            indicators[i].setBackgroundResource(R.drawable.icon_point);
        }
        if (indicators.length > selectedPosition)
            indicators[selectedPosition].setBackgroundResource(R.drawable.icon_point_pre);
    }

    private void initViewPager() {

        int indicatorSize = autoPlayImages.size();

        indicators = new ImageView[indicatorSize];

        for (int i = 0; i < indicators.length; i++) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_indicator, null);
            indicators[i] = (ImageView) view.findViewById(R.id.image_indicator);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(15, 15);
            layoutParams.setMargins(5, 0, 5, 0);
            indicators[i].setLayoutParams(layoutParams);
            indicatorLayout.addView(view);
        }

        viewList = AddImages.addImageDatas(getActivity(), autoPlayImages, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = (int) v.getTag();
            }
        });

        bannerAdapter = new MyViewPagerAdapter(viewList);
        viewPager.setAdapter(bannerAdapter);
        if (indicators.length > 1) {
            viewPager.setCurrentItem(1, false);
        }

    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            //整体厨房
            case R.id.rl_chufang:
                intent = new Intent(getActivity(), ChuFangActivity.class);
                startActivity(intent);

                break;
            //家居馆
            case R.id.rl_home:
                mainActivity.MyToast("家居馆");
                break;

            //工业化内装
            case R.id.rl_industry:
                intent = new Intent(getActivity(), IndustryFitmentActivity.class);
                startActivity(intent);
                break;

            //整体卫浴
            case R.id.rl_bathroom:
                intent = new Intent(getActivity(), EntiretyBathroomActivity.class);
                startActivity(intent);
                break;

            //安装
            case R.id.rl_install:
                //   mainActivity.MyToast("安装");
                intent = new Intent(getActivity(), InstallActivity.class);
                startActivity(intent);
                break;

            //设计
            case R.id.rl_design:
                mainActivity.MyToast("设计");
                break;

            //更多
            case R.id.rl_more:
                int index = (int) v.getTag();
                pagelist.get(index).setShow(!pagelist.get(index).isShow());
                listAdapter.notifyDataSetChanged();
                break;

            default:
                break;
        }
    }
}
